package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.AiRecordingMain;
import com.ruoyi.common.core.domain.entity.FileEspVo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;

import com.ruoyi.system.service.impl.FileUploadService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.domain.entity.SystemFile;
import com.ruoyi.system.service.ISystemFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

/**
 * 系统文件Controller
 *
 * @author ruoyi
 * @date 2025-03-06
 */

@RestController
@RequestMapping("/system/file")
public class SystemFileController extends BaseController
{
    @Autowired
    private ISystemFileService systemFileService;

    @Autowired
    private FileUploadService fileUploadService;



    /**
     * 录音文件上传
     */
    @Log(title = "录音文件上传", businessType = BusinessType.OTHER)
    @PostMapping("/fileUpload")
    public AjaxResult avatar(@RequestParam("file") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.uploadBig(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.MEDIA_WAV);
            return AjaxResult.success(avatar);
////            avatar.replace("/profile/", "/");
//            return toAjax(aiRecordingMainService.insertAiRecordingMainFile(avatar.replace("/profile/", "/"),avatar,language));
        }
        return error("上传文件异常，请联系管理员");
    }


    /**
     * 录音文件上传
     */
    @Log(title = "录音文件上传", businessType = BusinessType.OTHER)
    @PostMapping("/fileUploadText")
    public AjaxResult fileUploadText(@RequestParam("file") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            file.transferTo(new File("/path/to/save"));
            String avatar = FileUploadUtils.uploadBig(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.MEDIA_WAV);
            return AjaxResult.success(avatar);
////            avatar.replace("/profile/", "/");
//            return toAjax(aiRecordingMainService.insertAiRecordingMainFile(avatar.replace("/profile/", "/"),avatar,language));
        }
        return error("上传文件异常，请联系管理员");
    }


    @PostMapping("/chunk1")
    public CompletableFuture<AjaxResult> uploadChunk1(@RequestBody FileEspVo chunk) {
        System.out.println("已进入接口");
        long startTime = System.currentTimeMillis();
        CompletableFuture<AjaxResult>  result= fileUploadService.processChunk1(chunk);
        long endTime = System.currentTimeMillis();
        System.out.println("总耗时耗时: " + (endTime - startTime) + "ms");
        return result;
    }
    @PostMapping("/chunk")
    public AjaxResult uploadChunk(@RequestBody FileEspVo fileEspVo) {
        try {
            System.out.println("已进入接口");
            long startTime = System.currentTimeMillis();
            // 基本参数校验
            if (fileEspVo.getFileId() == null || fileEspVo.getChunkData() == null) {
                return AjaxResult.error("缺少必要参数");
            }
//            // 创建一个新线程执行异步任务
//            Thread thread = new Thread(() -> {
//                // 处理分块上传
                boolean isComplete = false;
//                try {
                    isComplete = fileUploadService.processChunk(fileEspVo);
                    System.out.println(isComplete);
                     long endTime = System.currentTimeMillis();
                     System.out.println("总耗时耗时: " + (endTime - startTime) + "ms");
                    if (isComplete) {
                        return AjaxResult.success("文件上传完成");
                    }
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//
//            // 启动线程
//            thread.start();
            return AjaxResult.success("分块接收成功");
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }




    /**
     * 查询系统文件列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(SystemFile systemFile)
    {
        startPage();
        List<SystemFile> list = systemFileService.selectSystemFileList(systemFile);
        return getDataTable(list);
    }

    /**
     * 导出系统文件列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:export')")
    @Log(title = "系统文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SystemFile systemFile)
    {
        List<SystemFile> list = systemFileService.selectSystemFileList(systemFile);
        ExcelUtil<SystemFile> util = new ExcelUtil<SystemFile>(SystemFile.class);
        util.exportExcel(response, list, "系统文件数据");
    }

    /**
     * 获取系统文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(systemFileService.selectSystemFileById(id));
    }

    /**
     * 新增系统文件
     */
    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @Log(title = "系统文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SystemFile systemFile)
    {
        return toAjax(systemFileService.insertSystemFile(systemFile));
    }

    /**
     * 修改系统文件
     */
    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "系统文件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SystemFile systemFile)
    {
        return toAjax(systemFileService.updateSystemFile(systemFile));
    }

    /**
     * 删除系统文件
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "系统文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(systemFileService.deleteSystemFileByIds(ids));
    }
}
